package com.tencent.crazypenguin.action;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.DatatypeConverter;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.tencent.crazypenguin.util.ConfigUtil;
import com.tencent.crazypenguin.util.JsonUtil;
import org.apache.struts2.StrutsStatics;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import net.sf.json.JSONObject;

public class Auth extends AbstractInterceptor {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private String results;



	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		JSONObject rspJson = new JSONObject();
		HttpServletResponse response = (HttpServletResponse) invocation
                .getInvocationContext().get(StrutsStatics.HTTP_RESPONSE);
		
		HttpServletRequest request = (HttpServletRequest) invocation
                .getInvocationContext().get(StrutsStatics.HTTP_REQUEST);
		
		PrintWriter out = response.getWriter();
		try {
			JSONObject postJson = JsonUtil.getPostData();
			request.setAttribute("userId", Long.parseLong(parseJWT(postJson.getString("token")).getId()));
		} catch (Exception e) {
			rspJson.put("error", e.getMessage());
			e.printStackTrace();
			out.println(rspJson.toString());
			out.flush();
			out.close();
			return null;
		}
		return invocation.invoke();
	}
	
	//Sample method to validate and read the JWT
	private Claims parseJWT(String jwt) {
	//This line will throw an exception if it is not a signed JWS (as expected)
		Claims claims = Jwts.parser()         
		   .setSigningKey(DatatypeConverter.parseBase64Binary(ConfigUtil.iGetConfig("tokenKey")))
		   .parseClaimsJws(jwt).getBody();
		
		return claims;
//		System.out.println("ID: " + claims.getId());
//		System.out.println("Subject: " + claims.getSubject());
//		System.out.println("Issuer: " + claims.getIssuer());
//		System.out.println("Expiration: " + claims.getExpiration());
	}

	public String getResults() {
		return results;
	}

	public void setResults(String results) {
		this.results = results;
	}
	
	
	
	

}
